using UnityEngine;
using System.Collections;

public class LevelEngine : MonoBehaviour 
{
	/// <summary>
	/// The amount of enemys in this level.
	/// </summary>
	public int amountEnemys;
	
	/// <summary>
	/// The player reference.
	/// </summary>
	public Transform playerReference;
	
	/// <summary>
	/// The enemy (a prefab).
	/// </summary>
	public GameObject enemy;
	
	/// <summary>
	/// Time to create enemys
	/// </summary>
	public float enemyTime;
	
	/// <summary>
	/// The distance from player.
	/// </summary>
	public float distance;
	
	/// <summary>
	/// The last tick.
	/// </summary>
	private float lastTick;
	
	// Use this for initialization
	void Start () 
	{
		lastTick = 0;
	}
	
	// Update is called once per frame
	void Update () 
	{
		if (canCreateEnemy())
		{
			createEnemys();
		}
	}
	
	/// <summary>
	/// if its time to create enemys
	/// </summary>
	/// <returns>
	/// 
	/// </returns>
	private bool canCreateEnemy()
	{
		if (Time.time >= lastTick + enemyTime)
		{
			lastTick = Time.time;
			return true;
		}
		return false;
	}
	
	/// <summary>
	/// Creates the enemys.
	/// </summary>
	private void createEnemys()
	{
		for (int k = 0; k < amountEnemys; k++)
		{
			Instantiate(enemy, generateEnemysPosition(), Quaternion.identity);
		}
	}
	
	/// <summary>
	/// Generates the enemys position.
	/// </summary>
	/// <returns>
	/// a position.
	/// </returns>
	private Vector3 generateEnemysPosition()
	{
		float angleA = playerReference.eulerAngles.x * Random.value;
		float angleB = playerReference.eulerAngles.z * Random.value;
		
		Vector3 vec = playerReference.position;
		vec.x += Mathf.Sin(angleA) * distance;
		vec.z += Mathf.Cos(angleB) * distance;
		
		return vec;
	}
}